package com.scs.application.core.utils;

import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.modules.base.entity.Hospital;
import com.scs.application.modules.base.entity.Supplier;
import com.scs.application.modules.upms.security.AnonymousUser;
import com.scs.application.modules.upms.security.UserPrincipal;
import org.apache.shiro.SecurityUtils;

/**
 * @description:
 */
public class UserUtils {

    /**
     * 当前用户。 如果未登录，返回匿名用户实例
     * @return
     */
    public static UserPrincipal currentUser(){
        try{
            Object principal = SecurityUtils.getSubject().getPrincipal();
            return (UserPrincipal) principal;
        }catch (Exception e){
            e.printStackTrace();
            return AnonymousUser.getInstance();
        }
    }

    /**
     * 获取医院ID
     * @return
     */
    public static String getHospitalId(){
        if (!currentUser().isHospital()) {
            throw new BusinessException("当前非医院身份，不允许操作");
        }
        return currentUser().getHospital().getId();
    }

    /**
     * 获取供应商ID
     * @return
     */
    public static String getSupplierId(){
        if (!currentUser().isSupplier()) {
            throw new BusinessException("当前非供应商身份，不允许操作");
        }
        return currentUser().getSupplier().getId();
    }

    public static boolean isAdmin(){
        return currentUser().isAdmin();
    }

    public static Hospital getHospital(){
        if(!currentUser().isHospital()){
            throw new BusinessException("当前非医院身份，不允许操作");
        }
        return currentUser().getHospital();
    }

    public static Supplier getSupplier(){
        if(!currentUser().isSupplier()){
            throw new BusinessException("当前非供应商身份，不允许操作");
        }
        return currentUser().getSupplier();
    }

    public static UserPrincipal getOpenPlatform(){

        UserPrincipal openPlatform = null;
        try{
            openPlatform = currentUser();
        }catch (ClassCastException cce){
        }

        if(openPlatform == null){
            throw new BusinessException("当前非开放平台身份！");
        }
        return openPlatform;
    }

    public static boolean isSupplier() {
        return currentUser().isSupplier();
    }
    public static boolean isHospital() {
        return currentUser().isHospital();
    }
    public static UserPrincipal currentUserInst() {
        return currentUser();
    }
}
